package com.ruoyi.common.core.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYY_MM_DD_C = "yyyy年MM月dd日";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyy年MM月dd日", "yyyy.M.d"};

    private static String[] weeks = new String[]{"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

    private static final String[] chineseNumbers = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] chineseMonths = {"", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
    private static final String[] chineseDays = {"", "一日", "二日", "三日", "四日", "五日", "六日", "七日", "八日", "九日", "十日", "十一日", "十二日",
            "十三日", "十四日", "十五日", "十六日", "十七日", "十八日", "十九日", "二十日", "二十一日", "二十二日", "二十三日", "二十四日", "二十五日", "二十六日",
            "二十七日", "二十八日", "二十九日", "三十日", "三十一日"};

    // 将阿拉伯数字年份转换为中文数字
    private static String arabicYearToChinese(int year) {
        StringBuilder chineseYear = new StringBuilder();
        for (char c : String.valueOf(year).toCharArray()) {
            chineseYear.append(chineseNumbers[Character.getNumericValue(c)]);
        }
        return chineseYear.toString() + "年";
    }

    // 将阿拉伯数字月份转换为中文
    private static String arabicMonthToChinese(int month) {
        return chineseMonths[month];
    }

    // 将阿拉伯数字日期转换为中文
    private static String arabicDayToChinese(int day) {
        return chineseDays[day];
    }

    // 将阿拉伯数字日期转换为中文日期表示
    public static String convertToChineseDate(int year, int month, int day) {
        return arabicYearToChinese(year) + arabicMonthToChinese(month) + arabicDayToChinese(day);
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return toDate(LocalDate.now());
    }

    /**
     * 获取当前Date型日期包含时分秒
     *
     * @return Date() 当前日期
     */
    public static Date getNowTime() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static Date getNextWeek(Integer format, Object dateStr) {
        try {
            // 将日期字符串转换为Date对象
            Date date = DateUtils.parseDate(dateStr.toString());

            // 使用Calendar类来进行日期计算
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.WEEK_OF_YEAR, 1);

            // 将结果转换为字符串格式并返回
            Date nextWeekDate = calendar.getTime();
            return nextWeekDate;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    public static void main(String[] args) {
        try {
            Date yxDate = DateUtils.parseDate("2024-02-28", DateUtils.YYYY_MM_DD);
            Date nowDate = DateUtils.parseDate("2024-03-01", DateUtils.YYYY_MM_DD);
            System.out.println(getDatePoor(yxDate, nowDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 比较Date数据类型的大小
     *
     * @param date  参数1
     * @param date2 参数2
     * @return
     */
    public static boolean dateCompare(Date date, Date date2) {
        boolean result = false;
        long time1 = date.getTime();
        long time2 = date2.getTime();
        if (time1 >= time2) {
            result = true;
        }
        return result;
    }


    /**
     * 获取指定日期是本月第几周的星期几
     *
     * @param date
     * @return
     */
    public static String getWeekOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.WEEK_OF_MONTH);
        int weekNum = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        String[] weeks = new String[]{"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        return "第" + week + "周" + weeks[weekNum];
    }

    /**
     * 获取指定日期下一(星期、月份、季度、半年、年）的开始日期。
     *
     * @param date
     * @return
     */
    public static Date getStartDayOfNext(Date date, int flag) {
        String[] dateArray = dateTime(date).split("-");//将日期转为年和月数组
        int year = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int value = getValueOfFlag(flag);
        if (value == -1) {//周检
            return getWeekFirstDayByDate(date, 1);
        } else if (value == 0) {//月
            if (month == 12) {
                year++;
                month = 1;
            } else {
                month++;
            }
            return parseDate(year + "-" + month + "-01");
        }
        if (month >= 10) {
            year++;
            month = 1;
        } else {
            month++;
        }
        int nextMonth = 0;
        //1000:赋予一个越大值，避免因代码bug出现死循环。
        for (int i = month; i < 1000; i++) {
            if (i > 12) {
                year++;
                i = 1;
            }
            if (i % value == 1) {
                nextMonth = i;
                break;
            }
        }
        return parseDate(year + "-" + nextMonth + "-01");
    }

    /**
     * 获取昨天日期（年月日）, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getyesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    }

    //flag:周期类型 1：一次性 2：周检 3：月检 4：季检 5：半年检 6：年检
    private static int getValueOfFlag(int flag) {
        int value = 0;
        switch (flag) {
            case 2:
                value = -1;
                break;
            case 3:
                value = 0;
                break;
            case 4:
                value = 3;
                break;
            case 5:
                value = 6;
                break;
            case 6:
                value = 12;
                break;
        }
        return value;
    }

    /**
     * 获取指定日期是本月第几周的星期几
     *
     * @param date
     * @return
     */
    public static String getWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int weekNum = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        String[] weeks = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        return weeks[weekNum];
    }

    /**
     * 获取指定日期后的第n个月的第一天
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfNextMonth(Date date, int amount) {
        Date nextMonth = DateUtils.addMonths(date, amount);
        return getFirstDayOfMonth(nextMonth);
    }

    /**
     * 获取指定日期所在月的第一天
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //获得本月第一天
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * 获取指定日期所在月的最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }

    /**
     * 获取指定日期指定的第几周的星期一所在的日期
     *
     * @param date
     * @param addWeek
     * @return
     */
    public static Date getWeekFirstDayByDate(Date date, int addWeek) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        //获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayWeek == 1) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day + 7 * addWeek);
        Date weekDate = cal.getTime();
        System.out.println(dateTime(weekDate));
        return weekDate;
    }

    /**
     * 获取指定日期所在的从周一至周五的日期和星期
     *
     * @param date
     * @param addWeek
     * @return
     */
    public static List<Map> getWeeksByDate(Date date, int addWeek) {
        List<Map> weekDateList = new ArrayList<>(7);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        //获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayWeek == 1) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        int day = cal.get(Calendar.DAY_OF_WEEK);
        int weekIndex = 1;
        Map weekDateMap = null;
        while (weekIndex <= 7) {
            if (weekIndex == 1)
                cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day + 7 * addWeek);
            else
                cal.add(Calendar.DATE, 1);
            Date mondayDate = cal.getTime();
            weekDateMap = new HashMap<>();
            weekDateMap.put("day", dateTime(mondayDate).split("-")[2]);
            weekDateMap.put("weekDate", mondayDate);
            weekDateMap.put("week", weeks[weekIndex - 1]);
            weekDateList.add(weekDateMap);
            weekIndex++;
        }
        return weekDateList;
    }

    public static String getStartAndEndDate(Date startDate, Date endDate, String joinStr, Integer pattern) {
        if (startDate == null && endDate == null) {
            return "";
        } else if (startDate != null && endDate == null) {
            return parseDateToStr(parsePatterns[pattern], startDate);
        } else if (startDate == null && endDate != null) {
            return parseDateToStr(parsePatterns[pattern], endDate);
        } else if (startDate != null && endDate != null && isSameDay(startDate, endDate)) {
            return parseDateToStr(parsePatterns[pattern], startDate);
        } else {
            String startDateStr = parseDateToStr(parsePatterns[pattern], startDate);
            String endDateStr = parseDateToStr(parsePatterns[pattern], endDate);
            if (startDateStr.startsWith(endDateStr.substring(0, 4))) {
                return startDateStr + joinStr + endDateStr.substring(5);
            }
            return startDateStr + joinStr + endDateStr;
        }
    }

    /**
     * 流程完成时间处理
     *
     * @param ms
     * @return
     */
    public static String getDate(long ms) {

        long day = ms / (24 * 60 * 60 * 1000);
        long hour = (ms / (60 * 60 * 1000) - day * 24);
        long minute = ((ms / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long second = (ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);

        if (day > 0) {
            return day + "天" + hour + "小时" + minute + "分钟";
        }
        if (hour > 0) {
            return hour + "小时" + minute + "分钟";
        }
        if (minute > 0) {
            return minute + "分钟";
        }
        if (second > 0) {
            return second + "秒";
        } else {
            return 0 + "秒";
        }
    }
}
